const path = require("path");
const http = require("https");
const url = require("url");
const cheerio = require("cheerio");
const puppeteer = require("puppeteer");

module.exports = {
  screenshot: async (url) => {
    console.log("screenshot");
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(url);

    // 对整个页面截图
    await page.screenshot({
      path: path.join(__dirname, "../public/capture.png"),
      type: "png",
      fullPage: true,
    });

    // 对页面某个元素截图
    let [element] = await page.$x("/html/body/header");
    await element.screenshot({
      path: path.join(__dirname, "../public/element.png"),
    });

    await page.close();
    await browser.close();
  },

  fetchHtmlData: (link) => {
    return new Promise(async (resolve, reject) => {
      try {
        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.goto(link);

        // await page.pdf({
        //   path: path.join(__dirname, "../public/element.pdf"),
        //   format: 'a4'
        // });

        const frame = page.frames().find((_) => _.name() === "contentFrame");
        let data = await frame.evaluate(function () {
          let list_n = document.querySelectorAll(".cmmts .itm .cnt a");
          let list_d = document.querySelectorAll(".cmmts .itm .cnt");
          let list_i = document.querySelectorAll(".cmmts .itm .head img");
          let data = [];
          for (let i = 0; i < list_n.length; i++) {
            let name = list_n[i].innerText;
            let icon = list_i[i].getAttribute("src");
            data.push({
              icon: icon.replace(/\/\r\n/g, "").trim(),
              name: name.trim(),
              desc: list_d[i].innerText
                .replace(name + "：", " ")
                .replace(/\/\r\n/g, "")
                .trim(),
            });
          }
          return data;
        });
        const imageUrl = await frame.$eval(".j-img", (el) => el.src);
        resolve(data);
        // console.log(imageUrl, url.parse(imageUrl), "[el");
        await page.close();
        await browser.close();
      } catch (error) {
        reject(error);
      }
    });
  },

  fetchHtmlInfo: (url) => {
    return new Promise((resolve, reject) => {
      http
        .get(url, (res) => {
          let html = "";
          res.on("data", (data) => {
            html += data;
          });
          res.on("end", () => {
            const $ = cheerio.load(html);
            const coverEl = $("#mainpic img").attr("src");
            resolve(coverEl);
          });
        })
        .on("error", (err) => {
          throw new Error();
        });
    });
  },
};
